package com.jackstraw.jack_base.mq.rocketmq.bean.listener;

import com.jackstraw.jack_base.mq.rocketmq.bean.TrListenerEntity;
import com.jackstraw.jack_base.util.ObjectUtil;
import com.jackstraw.jack_base.util.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.LocalTransactionState;
import org.apache.rocketmq.client.producer.TransactionListener;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class ProducerTransactionListener implements TransactionListener {

    @Override
    public LocalTransactionState executeLocalTransaction(Message msg, Object arg) {
        log.info("LocalTransactionState---Message:[{}]", msg);
        log.info("LocalTransactionState---Object:[{}]", arg);
        TrListenerEntity trListenerEntity = new TrListenerEntity();
        trListenerEntity.setArg(arg);
        trListenerEntity.setRocketmqMessage(msg);
        String producerTxServiceBeanName = String.valueOf(msg.getProperties().get(ProducerTxService.PRODUCER_TX_SERVICE_BEAN_NAME));
        ProducerTxService producerTxService = SpringUtil.getBean(producerTxServiceBeanName,ProducerTxService.class);
        if (ObjectUtil.ObjectUtilByLang3.isEmpty(producerTxService)) {
            log.error("ProducerTransactionListener#executeLocalTransaction---未找到处理事务的服务");
            return LocalTransactionState.ROLLBACK_MESSAGE;
        }
        return producerTxService.executeLocalTransaction(trListenerEntity).getLocalTransactionState();
    }


    @Override
    public LocalTransactionState checkLocalTransaction(MessageExt msg) {
        log.info("LocalTransactionState---MessageExt:[{}]", msg);
        TrListenerEntity trListenerEntity = new TrListenerEntity();
        trListenerEntity.setMessageExt(msg);
        String producerTxServiceBeanName = String.valueOf(msg.getProperties().get(ProducerTxService.PRODUCER_TX_SERVICE_BEAN_NAME));
        ProducerTxService producerTxService = SpringUtil.getBean(producerTxServiceBeanName,ProducerTxService.class);
        if (ObjectUtil.ObjectUtilByLang3.isEmpty(producerTxService)) {
            log.error("ProducerTransactionListener#checkLocalTransaction---未找到事务回查的服务");
            return LocalTransactionState.ROLLBACK_MESSAGE;
        }
        return producerTxService.checkLocalTransaction(trListenerEntity).getLocalTransactionState();
    }


}
